var express = require('express');
var router = express.Router();
var sqlobj = require('../db/sql_utils');
var moment = require('moment');
var connection = require('../db/db_utils');
var vertoken = require('../token/token');

router.post('/login', function (req, res) {
    const params = [];
    params[0] = req.body.username
    // params[1] = req.body.password
    console.log(params)
    if (params[0] === '' || params[1] === '') return res.json({code: 400,message: 'Account or password cannot be empty'})
    connection.query(sqlobj.sqls.loginUser, params, function (err, result) {
        if (err) return res.json({code:500,message: err})
        if (result.length == 0) return res.json({code:4002,message: 'The user does not exist' })
        if(result[0].password == req.body.password){
            vertoken.setToken(result[0].user_name, result[0].id).then(data => res.json({code: 200,message: 'login success', token: data}))
            return
        }
        return res.json({code:400,message: 'password error' })
        
    })
});
router.post('/register', function (req, res) {
    let params = [];
    params[0] = req.body.username
    params[1] = req.body.password
    params[2] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    if (params[0] === '' || params[1] === '') {
        return res.json({code: 1,message: 'Account or password cannot be empty'})
    } else {
        connection.query(sqlobj.sqls.register, params, function (error, data) {
            if (error) {
                if(error.sqlMessage.indexOf("Duplicate") != -1)return res.json({code: 400,message: "Username "+params[0]+" already exists"})
                return res.json({code: -1,message: error})
            } 
            return res.json({code: 200,message: 'Registered successfully' })
        })
    }
});

module.exports = router
